package com.mobimap.nhom9.dao;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import com.mobimap.nhom9.bus.MobimapProvider;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class MapSQLiteHelper extends SQLiteOpenHelper {
	
	private static int DATABASE_VERSION = 1;
	private static String DATABASE_PATH = MobimapProvider.APP_DATA_FOLDER;
	private static String DATABASE_NAME = "mobimap";
	private Context myContext;
	
	public MapSQLiteHelper(Context context) {
		super(context, DATABASE_PATH + DATABASE_NAME, null, DATABASE_VERSION);
		// TODO Auto-generated constructor stub
		this.myContext = context;
		this.createDatabase();

	}

	private void createDatabase() {
		// TODO Auto-generated method stub
		boolean dbExist = checkDataBase();
		if (!dbExist)
		{
			this.copyDatabase();
		}
	}
	private static boolean checkDataBase()
	{
		try
		{
			String myPath = DATABASE_PATH + DATABASE_NAME;

			File f = new File(myPath);

			if (f.exists())
			{
				return true;
			}
		}
		catch (SQLException e)
		{
			return false;
		}

		return false;
	}
	private void copyDatabase()
	{
		final int BUFFER = 2048;
		try
		{
			BufferedOutputStream dest = null;
			InputStream is = this.myContext.getAssets().open(DATABASE_NAME + ".zip");
			Log.e("MOBIMAP", "Load database stream: " + DATABASE_NAME + ".zip");
			ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is));
			ZipEntry entry;

			while ((entry = zis.getNextEntry()) != null)
			{
				int count;
				byte data[] = new byte[BUFFER];

				FileOutputStream fos = new FileOutputStream(DATABASE_PATH + entry.getName());
				dest = new BufferedOutputStream(fos, BUFFER);
				while ((count = zis.read(data, 0, BUFFER)) != -1)
				{
					dest.write(data, 0, count);
				}
				dest.flush();
				dest.close();
			}
			zis.close();
		}
		catch (IOException e)
		{
			System.out.println(e.getMessage());
			throw new Error("Error copying database");
		}
	}
	@Override
	public void onCreate(SQLiteDatabase arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
		// TODO Auto-generated method stub
		
	}
}
